package com.cyj.springbootservice.controller.mybatisplus;

import com.cyj.springbootservice.api.entity.User;
import com.cyj.springbootservice.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:  mybatis-plus 对乐观锁的实现
 * @Author C_Y_J
 * @create 2021/10/7 10:33
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {

    private UserMapper userMapper;

    /**
     * 测试版本号（乐观锁）
     * <p>
     * 当要更新一条记录的时候，希望这条记录没有被别人更新
     * 乐观锁实现方式：
     * <p>
     * 取出记录时，获取当前version
     * 更新时，带上这个version
     * 执行更新时， set version = newVersion where version = oldVersion
     * 如果version不对，就更新失败
     */
    @PostMapping("/update")
    public void Update() {
        User user1 = userMapper.selectById(1);
        User user2 = userMapper.selectById(1);

        user2.setUserName("唐僧");
        System.out.println("更新的条数：" + userMapper.updateById(user2));

        user1.setUserName("孙悟空");
        System.out.println("更新的条数：" + userMapper.updateById(user1));

    }
}
